var PublicFun = require('./Function'),
	http = require("http"),
	socketIo = require('socket.io')(http);

var server = http.createServer().listen(8080);
socketIo.listen(server);

var clientList = {};
socketIo.on('connection', function(socket) {
	// socketIo.emit('login', {msg: '欢迎'});

	if(!clientList.hasOwnProperty(socket.id)){
		clientList[socket.id] = socket;
	}

	socket.on('toSelf', function(data) {
		socket.emit(data.EventName, data.Data);	//发给自己
	});
	socket.on('toOther', function(data) {
		socket.broadcast.emit(data.EventName, data.Data);		//发送除开自己的其他所有人
	});
	socket.on('toAll', function(data) {
		socketIo.emit(data.EventName, data.Data);	//发给所有人，包括自己
	});

	socket.on('joinRoom', function(data) {
		socket.join(data.RoomName);
	});
	socket.on('leaveRoom', function(data) {
		socket.leave(data.RoomName);
	});
	socket.on('toRoom', function(data) {
		socket.broadcast.to(data.RoomName).emit(data.EventName, data.Data);			//向一个房间广播消息（发送者收不到消息)
	});
	socket.on('inRoom', function(data) {
		socketIo.in(data.RoomName).emit(data.EventName, data.Data);		//向一个房间广播消息（包括发送者都能收到消息)
	});

	socket.on('disconnect', function () {
		// socketIo.emit('logout', socket.name + ':用户退出');
		if(clientList.hasOwnProperty(socket.id)){
			delete clientList[socket.id];
		}
	});
	//程序调用，主动断开
	socket.on('clientDisconnect', function () {
		socket.destroy();
		if(clientList.hasOwnProperty(socket.id)){
			delete clientList[socket.id];
		}
	});

	socket.on('error', function (err) {
		if (err) {
            try {
            	PublicFun.errorLog("Scoket错误", "Socket异常关闭");
            } catch (err) {
                PublicFun.errorLog("Scoket错误", "Socket异常关闭");
            }

            if(clientList.hasOwnProperty(socket.id)){
				delete clientList[socket.id];
			}
        }
	});
});

//发送给指定连接
exports.emitBySocketId = function(socketId, eventName, data){
	if(clientList.hasOwnProperty(socketId)){
		clientList[socketId].emit(eventName, data);
	}
}

//广播给所有人
exports.emit = function(eventName, data){
	socketIo.emit(eventName, data);
};
//广播给该房间的所有人
exports.emitRoom = function(eventName, roomName, data){
	socketIo.in(roomName).emit(eventName, data);			//广播给所有人，包括自己
};
